package com.karina.visualization.chart.client;

import java.util.List;

import com.karina.visualization.chart.component.ColumnSeries;
import com.karina.visualization.chart.component.CoordinateChart;
import com.karina.visualization.chart.component.CoordinateChartWidget;
import com.karina.visualization.chart.component.UpdateableObject;
import com.karina.visualization.chart.component.XAxis;
import com.karina.visualization.chart.model.CategorizedSeriesModel;
import com.karina.visualization.chart.model.ColumnChartModel;
import com.karina.visualization.chart.model.SeriesModel;
import com.karina.visualization.chart.skins.CoordinatePaneSkinImpl;
import com.karina.visualization.styles.CSSDeclaretions;
import com.karina.visualization.styles.StylesManager;

public class ColumnChartWidget<DataType> extends
		CoordinateChartWidget<ColumnChartModel<DataType>, DataType> {
	@SuppressWarnings("rawtypes")
	static class ColumnChart extends CoordinateChart {

		private final static int MARGIN = 30;

		@SuppressWarnings("unchecked")
		ColumnChart() {
			super(null, new CoordinatePaneSkinImpl(true));
		}

		@Override
		protected Series createSeries(SeriesModel model) {
			return new ColumnSeries((CategorizedSeriesModel) model);
		}

		@SuppressWarnings({ "unchecked" })
		@Override
		protected void caculateChartObjectModelProperties() {
			super.caculateChartObjectModelProperties();

			List<Series> serieses = getSeries();
			XAxis xaxis = getXaxis();
			List<String> categories = xaxis.getData().getCategories();

			int size = categories.size();
			int width = (int) (getData().getWidth() - xaxis.getData()
					.getTextMargin());
			int gap = width / size;

			CSSDeclaretions style = StylesManager.getIntance().getStyle(
					".BarChart.Series");
			Integer maxWidth = (Integer) style.getStyle("maxWidth");

			int margin = MARGIN;
			int defaultWidth = (gap - margin * 2) / serieses.size();
			if (maxWidth != null && defaultWidth > maxWidth) {
				defaultWidth = maxWidth;
				margin = (gap - defaultWidth * serieses.size()) / 2;
			}

			int initialX = margin;

			for (Series series : serieses) {
				((UpdateableObject<SeriesModel>) series).getData().setWidth(
						defaultWidth);
				((UpdateableObject<SeriesModel>) series).getData()
						.setRelativeX(initialX);
				initialX += defaultWidth;
			}
		}

		@Override
		public String getSelectorName() {
			return "BarChart";
		}
	}

	public ColumnChartWidget() {
		super(new ColumnChart());
		setChartStyle("BarChart.ColumnSeries", "maxWidth", 50);
	}

	@Override
	protected ColumnChartModel<DataType> createChartModel(
			List<DataType> dataProvider) {
		return new ColumnChartModel<DataType>(dataProvider);
	}

}
